<template>
  <div>
    <div class="qup-page-heade bread-box">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" @click.native="goBack(false)">常规奖惩管理</el-breadcrumb-item>
        <el-breadcrumb-item>详情</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button size="mini" @click.native="goBack(false)">返回</el-button>
      </div>
    </div>
    <div v-loading="loading">
      <el-form
        ref="refForm"
        style="margin-top:20px"
        :model="formData"
        :rules="rules"
        size="mini"
        label-width="150px"
      >
        <el-row>
          <el-col v-if="flag !=='new' " :span="8">
            <el-form-item label="奖惩编码:" prop="rewardPunishmentCode">
              {{ formData.rewardPunishmentCode }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="奖惩名称:" prop="rewardPunishmentName">
              <el-input v-model="formData.rewardPunishmentName" :disabled="disabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户编码:" prop="customerItem">
              <span v-if="flag !== 'new'">{{ formData.customerCode }}</span>
              <input-with-dialog
                v-else
                ref="refSearchType"
                v-model="formData.customerItem"
                :props="{label:'code',value:'code'}"
                :disabled="flag!=='new'"
                :config="clientConfig"
                @change="clientChoose"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称:" prop="customerName">
              {{ formData.customerName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务账号编码:" prop="businessAccount">
              <span v-if="flag !=='new'">{{ formData.businessAccountCode }}</span>
              <el-select
                v-else
                v-model="formData.businessAccount"
                :disabled="!formData.customerName"
                filterable
                :placeholder="!formData.customerName?'请先选择客户编码':'输入搜索'"
                @change="businessAccChange"
              >
                <el-option
                  v-for="item in businessAccountList"
                  :key="item.businessAccountCode"
                  :label="item.businessAccountCode"
                  :value="item"
                >
                  <span style="float: left">{{ item.businessAccountCode }}</span>
                  <span style="float: right; color: #8492a6;font-weight:500; font-size: 12px">{{ item.businessAccountName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="业务账号名称:" prop="shopCode">
              {{ formData.businessAccount?formData.businessAccount.businessAccountName:'' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属办事处:" prop="shopCode">
              {{ formData.agencyName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="办事处性质:" prop="agencyType">
              {{ matchDict(formData.agencyType, 'OFFICE_NATURE') }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="通报类别:" prop="notificationType">
              <el-select v-model="formData.notificationType" :disabled="disabled">
                <el-option
                  v-for="item in dictMap['CIRCULATE_TYPE']"
                  :key="item.id"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件编号:" prop="fileNumber">
              <el-input v-model="formData.fileNumber" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件名称:" prop="fileName">
              <el-input v-model="formData.fileName" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发文部门:" prop="dispatchDepartmentName">
              <el-input v-model="formData.dispatchDepartmentName" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据来源:" prop="dataSource">
              {{ formData.dataSource===1?'手工新增':'BPM' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="BPM流程号:" prop="bpmNumber">
              <el-input v-model="formData.bpmNumber" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建人:" prop="applicantName">
              {{ formData.applicantName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间:" prop="applyTime">
              {{ formData.applyTime }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="启用状态:" prop="enable">
              {{ formData.enable===1?'启用':'禁用' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人AD账号:" prop="applicantCode">
              {{ formData.applicantCode }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人姓名:" prop="applicantName">
              {{ formData.applicantName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请时间:" prop="applyTime">
              {{ formData.applyTime }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :span="8">
            <el-form-item label="奖惩类别:" prop="rewardPunishmentCategory">
              <el-select v-model="formData.rewardPunishmentCategory" :disabled="disabled">
                <el-option
                  v-for="item in dictMap['SHOP_REWARD_PUNISH_TYPE']"
                  :key="item.id"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              v-if="formData.rewardPunishmentCategory==='B'"
              label="处罚金额类型:"
              prop="penaltyType"
            >
              <el-select v-model="formData.penaltyType" :disabled="disabled">
                <el-option
                  v-for="item in dictMap['FINE_TYPE']"
                  :key="item.id"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="奖励金额:" prop="rewardAmount">
              <el-input v-model="formData.rewardAmount" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划处罚金额:" prop="plannedPenaltyAmount">
              <el-input v-model="formData.plannedPenaltyAmount" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库房占用费:" prop="warehouseOccupancyFee">
              <el-input v-model="formData.warehouseOccupancyFee" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账务日期:" prop="financeDate">
              <el-date-picker
                v-model="formData.financeDate"
                :disabled="disabled"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="奖惩原因:" prop="disciplinaryReasons">
              <el-input v-model="formData.disciplinaryReasons" type="textarea" :disabled="disabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="flag !=='new'" :gutter="0">
          <el-col :span="8">
            <el-form-item label="是否有减免:" prop="isDerate">
              {{ formData.isDerate===1?'是':'否' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="减免金额:" prop="derateAmount">
              {{ formData.derateAmount }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际处罚金额:" prop="actualPenaltyAmount">
              {{ formData.actualPenaltyAmount }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="减免原因:" prop="derateReasons">
              {{ formData.derateReasons }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="减免申请人AD账号:" prop="derateApplicantCode">
              {{ formData.derateApplicantCode }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="减免申请时间:" prop="derateApplicantName">
              {{ formData.derateApplicantName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="减免流程号:" prop="derateNumber">
              {{ formData.derateNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="减免文件类型:" prop="derateFileType">
              {{ matchDict(formData.derateFileType, 'DERATE_FILE_TYPE') }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="减免类别:" prop="derateType">
              {{ matchDict(formData.derateType, 'DERATE_TYPE') }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="flag !=='view' " :gutter="0">
          <el-col :span="24" style="text-align:center;padding-bottom:20px;">
            <el-button type="default" @click="goBack(false)">取消</el-button>
            <el-button type="primary" :loading="loading" @click="confirm">确认</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getDictByPatchType } from '@/api/dataDict'
import { } from '@/api/common.js'
import { queryRPById, addRP, modifyRP } from '@/api/rewardsPunishment'
import { getBusinessAccount } from '@/api/common'
import { getUserInfo } from '@/utils/auth'
import { getSigningRealEstateCustomer } from '@/api/channelTaskMng'
import BackPageMixin from '@/mixins/backPage'
export default {
  name: 'DetailChannelTask',
  components: { },
  mixins: [BackPageMixin],
  props: {
    flag: {
      type: String,
      default() {
        return 'new'
      }
    },
    id: {
      type: String,
      default: ''
    },
    row: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      dictMap: {},
      signingRealEstateCustomer: '',
      formData: {
        rewardPunishmentName: '',
        customerItem: [],
        customerName: '',
        dataSource: 1,
        enable: 1,
        businessAccount: {}
      },
      rules: {
        rewardPunishmentName: [{ required: true, message: '请输入奖惩名称', trigger: 'blur' }],
        customerItem: [{ required: true, message: '请选择客户编码', trigger: 'change' }],
        businessAccount: [{ required: true, message: '请选择业务账号编码', trigger: 'change' }],
        notificationType: [{ required: true, message: '请选择通报类别', trigger: 'change' }],
        bpmNumber: [{ required: true, message: '请输入BPM流程号', trigger: 'blur' }],
        rewardPunishmentCategory: [{ required: true, message: '请选择奖惩类别', trigger: 'change' }],
        penaltyType: [{ required: true, message: '请选择处罚金额类型', trigger: 'change' }]
      },
      clientConfig: {
        title: '客户',
        apiHeader: {
          'permission-code': 'routine',
          'Permission-App': 'slm'
        },
        interfacePath: `/select-service/api/v1/customer/page`,
        setting: [
          {
            prop: 'code',
            title: '编码'
          },
          {
            prop: 'name',
            title: '名称'
          }
        ]
      },
      businessAccountList: []
    }
  },
  computed: {
    disabled() {
      return this.flag === 'view'
    }
  },
  watch: { },
  async created() {
    await this.getDictByPatchTypeAll()
    const { userName } = getUserInfo()
    if (this.flag === 'new') {
      this.formData.applicantName = userName
    }
    if (this.flag !== 'new') {
      this.loading = true
      try {
        const detail = await queryRPById(this.row.id)
        if (detail.success === 1) {
          this.patchDetail(detail.data)
        } else {
          this.$message.warning(detail.msg)
        }
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    }
  },
  methods: {
    patchDetail(data) {
      for (const key in data) {
        const ele = data[key]
        this.$set(this.formData, key, ele)
      }

      this.formData.customerItem = [{
        label: data.customerName,
        value: data.customerCode
      }]
      this.formData.businessAccount = {
        businessAccountCode: data.businessAccountCode,
        businessAccountName: data.businessAccountName
      }
    },
    matchDict(val, type) {
      if (val == null || val === 'undefined') return ''
      const list = this.dictMap[type]
      const valArr = (val).toString().split(',')
      if (valArr.length > 1) {
        let str = ''
        for (let i = 0; i < valArr.length; i++) {
          const ele = valArr[i]
          const filterItem = list.filter(item => item.dictCode === ele)
          str += (filterItem[0] && filterItem[0].dictName || '') + ','
        }
        return str.substring(0, str.length - 1)
      }
      const filterItem = list.filter(item => item.dictCode === val.toString())
      return filterItem[0] && filterItem[0].dictName || ''
    },
    async getDictByPatchTypeAll() {
      const dictRes = await getDictByPatchType(['DERATE_TYPE', 'DERATE_FILE_TYPE', 'FINE_TYPE', 'OFFICE_NATURE', 'CIRCULATE_TYPE', 'SHOP_REWARD_PUNISH_TYPE'])
      this.$set(this, 'dictMap', dictRes)
    },
    clientChoose(row) {
      this.formData.customerCode = row[0].code
      this.formData.customerName = row[0].name
      this.formData.agencyName = row[0].agencyName
      this.formData.agencyCode = row[0].agencyCode
      this.businessAccountList = []
      this.formData.businessAccount = ''
      this.getSigningRealEstateCustomer(row[0].code)
      this.getBuinessCode()
    },
    async getBuinessCode() {
      // 获取业务账号
      await getBusinessAccount(this.formData.customerItem[0].code, 'shopdesign').then(res => {
        if (res.success) {
          res.data.records.map(el => {
            this.businessAccountList.push({
              businessAccountCode: el.code,
              businessAccountName: el.name,
              businessAccountType: el.accountTypeName
            })
          })
        }
      })
    },
    businessAccChange(val) {
      this.formData.businessAccountName = val.businessAccountName
      this.formData.businessAccountCode = val.businessAccountCode
    },
    async getSigningRealEstateCustomer(code) {
      const data = await getSigningRealEstateCustomer(code)
      this.formData.agencyType = data.agencyNature
    },
    async checkForm() {
      return new Promise((resolve, reject) => {
        this.$refs.refForm.validate((valid) => {
          if (valid) {
            resolve(true)
          } else {
            resolve(false)
          }
        })
      })
    },
    async confirm() {
      const chkSuccess = await this.checkForm()
      if (!chkSuccess) return
      const params = {}
      const formData = this.formData
      const ignoreKey = ['businessAccount', 'customerItem']
      for (const key in formData) {
        const element = formData[key]
        if (!ignoreKey.includes(key))params[key] = element
      }
      this.loading = true
      try {
        this.flag === 'new' ? await addRP(params) : await modifyRP(params)
        this.$message.success(this.flag === 'new' ? '创建成功' : '编辑成功')
        setTimeout(() => {
          this.goBack(true)
        }, 800)
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    goBack(flag) {
      this.$emit('close', flag)
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-breadcrumb__inner{
  color: $qup-color-primary;
}
.el-select, .el-date-editor.el-input{
  width:100%;
}
</style>
